<template>
    <div class="user">
        <el-form :inline="true" :model="searchParam" class="demo-form-inline">
            <el-form-item>
                <el-input
                    clearable
                    v-model="searchParam.nickName"
                    placeholder="昵称"
                />
            </el-form-item>
            <el-form-item>
                <el-select clearable v-model="searchParam.sex" placeholder="请选择性别">
                    <el-option label="男" value="1"/>
                    <el-option label="女" value="2"/>
                    <el-option label="未知" value="3"/>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-select clearable v-model="searchParam.schoolUuid" placeholder="请选择学校">
                    <el-option v-for="school in data.schools" :key="school.uuid" :label="school.name"
                               :value="school.uuid"/>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-select
                    clearable
                    v-model="searchParam.disabled"
                    placeholder="请选择状态"
                >
                    <el-option label="启用" value="false"/>
                    <el-option label="禁用" value="true"/>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-select
                    clearable
                    v-model="searchParam.sourceType"
                    placeholder="请选择来源类型"
                >
                    <el-option label="注册" value="1"/>
                    <el-option label="手机" value="2"/>
                    <el-option label="QQ" value="3"/>
                    <el-option label="微信" value="4"/>
                </el-select>
            </el-form-item>
            <el-form-item style="width: auto">
                <el-button type="primary" @click="search" size="small">查询</el-button>
                <el-button type="primary" @click="exportUserData" size="small">导出用户</el-button>
                <el-button type="warning" @click="batchDisableUser" size="small">批量禁用</el-button>
                <el-button type="success" @click="batchEnableUser" size="small">批量启用</el-button>
                <el-button type="danger" @click="batchDeleteUser" size="small">批量删除</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="data.users" border style="width: 100%" v-loading="data.loading"
                  element-loading-text="拼命加载中" @selection-change="handleSelectionChange">
            <el-table-column type="selection" align="center" width="70px"/>
            <el-table-column fixed prop="avatar" label="头像" align="center" width="150px">
                <template #default="scope">
                    <el-avatar
                        :src="scope.row.avatar"
                    />
                </template>
            </el-table-column>
            <el-table-column prop="nickName" label="昵称" align="center" width="150px"/>
            <el-table-column prop="schoolName" label="所属学校" align="center" width="150px"/>
            <el-table-column prop="sex" label="性别" align="center" width="150px">
                <template #default="scope">
                    <el-tag
                        v-show="scope.row.sex === 1" type="primary"
                        disable-transitions
                    >男
                    </el-tag>
                    <el-tag
                        v-show="scope.row.sex === 2" type="success"
                        disable-transitions
                    >女
                    </el-tag>
                    <el-tag
                        v-show="scope.row.sex === 3" type="info"
                        disable-transitions
                    >未知
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="disable" label="状态" align="center" width="150px">
                <template #default="scope">
                    <el-tag
                        :type="scope.row.disabled === false ? 'success' : 'danger'"
                        disable-transitions
                    >{{ scope.row.disabled === false ? "启用" : "禁用" }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="isSetBasicMessage" label="设置基本信息" align="center" width="150px">
                <template #default="scope">
                    <el-tag
                        :type="scope.row.isSetBasicMessage === true ? 'success' : 'danger'"
                        disable-transitions
                    >{{ scope.row.isSetBasicMessage === true ? "是" : "否" }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="phone" label="手机号" align="center" width="150px"/>
            <el-table-column prop="ipaddress" label="ip地址" align="center" width="150px"/>
            <el-table-column prop="backgroundImage" label="背景图" align="center" width="150px">
                <template #default="scope">
                    <el-image style="width: 50px; height: 50px" :src="scope.row.backgroundImage" fit="contain">

                    </el-image>
                </template>
            </el-table-column>
            <el-table-column prop="sex" label="来源类型" align="center" width="150px">
                <template #default="scope">
                    <el-tag
                        v-show="scope.row.sourceType === 1" type="primary"
                        disable-transitions
                    >注册
                    </el-tag>
                    <el-tag
                        v-show="scope.row.sourceType === 2" type="success"
                        disable-transitions
                    >手机
                    </el-tag>
                    <el-tag
                        v-show="scope.row.sourceType === 3" type="info"
                        disable-transitions
                    >QQ
                    </el-tag>
                    <el-tag
                        v-show="scope.row.sourceType === 4" type="info"
                        disable-transitions
                    >微信
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column
                prop="createTime"
                label="创建时间"
                width="180"
                align="center"
            >
            </el-table-column>
            <el-table-column
                prop="updateTime"
                label="更新时间"
                width="180"
                align="center"
            >
            </el-table-column>
            <el-table-column label="操作" width="350">
                <template #default="scope">
                    <el-button
                        class="button-space"
                        @click="enableUser(scope.row.uuid)"
                        v-if="scope.row.disabled"
                        type="success"
                        size="small"
                    >启用
                    </el-button>
                    <el-button
                        class="button-space"
                        @click="disableUser(scope.row.uuid)"
                        v-if="!scope.row.disabled"
                        type="warning"
                        size="small"
                    >禁用
                    </el-button>
                    <el-button
                        class="button-space"
                        @click="toEdit(scope.row.uuid)"
                        v-if="scope.row.isSetBasicMessage"
                        type="info"
                        size="small"
                    >修改信息
                    </el-button>
                    <el-button
                        class="button-space"
                        @click="showResetPassword(scope.row)"
                        v-if="scope.row.isSetBasicMessage"
                        type="info"
                        size="small"
                    >重置密码
                    </el-button>
                    <el-popconfirm
                        title="你确定要删除该用户吗？"
                        confirm-button-text="是"
                        cancel-button-text="否"
                        @confirm="deleteUser(scope.row.uuid)"
                    >
                        <template #reference>
                            <el-button
                                class="button-space"
                                type="danger"
                                size="small"
                            >删除
                            </el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
            background
            layout="prev, pager, next"
            :total="data.total"
            style="text-align: center; margin-top: 10px"
            @current-change="currentChange"
        >
        </el-pagination>
        <el-dialog v-model="data.showPasswordDialogVisible" title="重置密码" width="30%" center>
            <span style="text-align: center">确定要重置用户【{{ data.resetPasswordNickName }}】密码吗？</span>
            <template #footer>
              <span class="dialog-footer">
        <el-button @click="data.showPasswordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmResetPassword">
          确定
        </el-button>
      </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import {onMounted, reactive} from "vue";
import {
    page,
    enable,
    disable,
    deleted,
    exportUser,
    batchDisable,
    batchEnable,
    batchDelete,
    resetPassword
} from "@/api/user/user";
import {all} from "@/api/school/school";
import {ElMessage, ElMessageBox, ElLoading} from "element-plus";
import dayjs from "dayjs";
import {useRouter} from "vue-router";

export default {
    setup() {
        const searchParam = reactive({
            loginName: '',
            disabled: '',
            schoolUuid: '',
            sex: '',
            page: 1,
            size: 10,
            sourceType: ''
        })
        const data = reactive({
            users: [],
            total: 0,
            loading: false,
            schools: [],
            selectUuids: [],
            showPasswordDialogVisible: false,
            resetPasswordNickName: '',
            resetPasswordUserUuid: '',
        })
        const router = useRouter();
        /**
         * 分页查询用户
         * @returns {Promise<void>}
         */
        const pageSearchUser = async () => {
            data.loading = true
            page(searchParam).then(res => {
                data.users = res.data.records
                data.total = res.data.total
            }).finally(() => {
                data.loading = false
            })
        }

        /**
         * 启用用户
         */
        const enableUser = async (uuid) => {
            enable(uuid).then(() => {
                ElMessage({
                    message: '启用成功',
                    type: 'success',
                })
                pageSearchUser()
            })
        }

        /**
         * 禁用用户
         */
        const disableUser = async (uuid) => {
            disable(uuid).then(() => {
                ElMessage({
                    message: '禁用成功',
                    type: 'success',
                })
                pageSearchUser()
            })
        }
        /**
         * 删除用户
         * @param uuid
         * @returns {Promise<void>}
         */
        const deleteUser = async (uuid) => {
            deleted(uuid).then(() => {
                ElMessage({
                    message: '删除成功',
                    type: 'success',
                })
                pageSearchUser()
            })
        }
        /**
         * 搜索查询用户
         * @returns {Promise<void>}
         */
        const search = async () => {
            page(searchParam).then(res => {
                data.users = res.data.records
                data.total = res.data.total
            })
        }

        /**
         * 获取全部学校
         * @returns {Promise<void>}
         */
        const allSchool = async () => {
            all().then(res => {
                data.schools = res.data
            })
        }
        /**
         * 导出用户数据
         */
        const exportUserData = () => {
            const loading = ElLoading.service({
                lock: true,
                text: '导出中...',
                background: 'rgba(0, 0, 0, 0.7)',
            })
            exportUser(searchParam).then(res => {
                const blob = new Blob([res]);
                const day = dayjs().format('YYYY-MM-DD');
                const fileName = `用户列表${day}.xls`;
                const elink = document.createElement('a');
                elink.download = fileName;
                elink.style.display = 'none';
                elink.href = URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                URL.revokeObjectURL(elink.href); // 释放URL 对象
                document.body.removeChild(elink);
                loading.close()
            })
        }
        /**
         * 批量选中
         * @param selection
         */
        const handleSelectionChange = (selection) => {
            data.selectUuids = selection.map(select => {
                return select.uuid
            })
        }
        /**
         * 批量禁用
         */
        const batchDisableUser = () => {
            if (data.selectUuids.length <= 0) {
                ElMessage({
                    message: '至少选择一个用户',
                    type: 'warning',
                })
                return
            }
            batchDisable(data.selectUuids).then(() => {
                ElMessage({
                    message: '禁用成功',
                    type: 'success',
                })
                data.selectUuids = []
                pageSearchUser();
            })
        }
        /**
         * 批量启用
         */
        const batchEnableUser = () => {
            if (data.selectUuids.length <= 0) {
                ElMessage({
                    message: '至少选择一个用户',
                    type: 'warning',
                })
                return
            }
            batchEnable(data.selectUuids).then(() => {
                ElMessage({
                    message: '禁用成功',
                    type: 'success',
                })
                data.selectUuids = []
                pageSearchUser();
            })
        }
        /**
         * 批量删除
         */
        const batchDeleteUser = () => {
            if (data.selectUuids.length <= 0) {
                ElMessage({
                    message: '至少选择一个用户',
                    type: 'warning',
                })
                return
            }
            ElMessageBox.confirm(
                '确定要删除所选用户吗?删除后不能恢复',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            )
                .then(() => {
                    batchDelete(data.selectUuids).then(() => {
                        ElMessage({
                            type: 'success',
                            message: '删除成功',
                        })
                        data.selectUuids = []
                        pageSearchUser();
                    })
                })
                .catch(() => {
                    ElMessage({
                        type: 'info',
                        message: '取消删除',
                    })
                    data.selectUuids = []
                })
        }
        /**
         * 分页
         * @param value
         */
        const currentChange = (value) => {
            searchParam.page = value
            pageSearchUser()
        }
        /**
         * 跳转到修改用户信息
         * @param uuid
         */
        const toEdit = (uuid) => {
            router.push({path: '/user/edit', query: {uuid: uuid}})
        }
        /**
         * 显示重置密码对话框
         * @param row
         */
        const showResetPassword = (row) => {
            console.log(row)
            data.showPasswordDialogVisible = true
            data.resetPasswordNickName = row.nickName
            data.resetPasswordUserUuid = row.uuid
        }
        /**
         * 确认重置密码
         * @param uuid
         */
        const confirmResetPassword = () => {
            resetPassword(data.resetPasswordUserUuid).then(() => {
                ElMessage({
                    type: 'success',
                    message: '重置密码成功',
                })
                data.showPasswordDialogVisible = false
            })
        }
        onMounted(() => {
            pageSearchUser()
            allSchool()
        })
        return {
            data,
            searchParam,
            enableUser,
            disableUser,
            search,
            deleteUser,
            allSchool,
            exportUserData,
            handleSelectionChange,
            batchDisableUser,
            batchEnableUser,
            batchDeleteUser,
            currentChange,
            toEdit,
            showResetPassword,
            confirmResetPassword
        }
    }
}
</script>

<style scoped>
.dialog-footer button:first-child {
    margin-right: 10px;
}
</style>